/**
 * Created with JetBrains WebStorm.
 * User: 可乐加糖
 * Date: 13-7-21
 * Time: 下午11:09
 * To change this template use File | Settings | File Templates.
 */

var net = require("net");

var charServer = net.createServer(), clientList = [];
charServer.on("connection", function (client) {
    client.name = client.remoteAddress + ":" + client.remotePort;
    client.write("Hi " + client.name + "!\n");
    console.log(client.name + "join...");
    clientList.push(client);
    //接入连接
    client.on("data", function (data) {
        broadcast(data, client)
    });
    //断开连接
    client.on("end",function(){
        console.log(client.name + "quit");
       clientList.splice(clientList.indexOf(client),1);
    });

    client.on("error",function(e){
        console.log(e);
    })
});
function broadcast(message, client) {
    for (var i = 0, icount = clientList.length; i < icount; i++) {
        if (client !== clientList[i]) {
            if(client[i].writable){
                clientList[i].write(client.name + " says " + message);
            }else{
                cleanup.push(clientList[i]);
                clientList[i].destroy();
            }
        }
    }
}
charServer.listen(9000);
console.log("Server is running...");